package org.example;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantReadWriteLock;

// TODO 需要注释
public class SimpleReentrantReadWriteLock {
    private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

    private volatile Map<String, Object> cache = new HashMap();

    public void write(String key, Object value) {
        try {
            lock.writeLock().lock();
            System.out.println(Thread.currentThread().getName() + " 正在写入：" + key);
            Thread.sleep(300);
            cache.put(key, value);
            System.out.println(Thread.currentThread().getName() + " 写入完成");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.writeLock().unlock();
        }
    }

    public void read(String key) {
        try {
            lock.readLock().lock();
            System.out.println(Thread.currentThread().getName() + " 正在读取");
            Thread.sleep(200);
            Object result = cache.get(key);
            System.out.println(Thread.currentThread().getName() + " 读取完成：" + result);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.readLock().unlock();
        }
    }

    public static void main(String[] args) {
        final SimpleReentrantReadWriteLock simpleLock = new SimpleReentrantReadWriteLock();

        for (int i = 1; i <= 5; i++) {
            final int tmp = i;
            new Thread(() -> {
                simpleLock.write(tmp + "", tmp + "");
            }, "t" + i).start();
        }

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        for (int i = 1; i <= 5; i++) {
            final int tmp = i;
            new Thread(() -> {
                simpleLock.read(tmp + "");
            }, "t" + i).start();
        }

    }
}
